package com.topisv.tms.platform.yhd;

import java.io.PrintWriter;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.taobao.api.internal.util.WebUtils;
import com.topisv.tms.entity.User;
import com.topisv.tms.platform.yhd.vo.YhdSessionKeyVo;
import com.topisv.tms.service.CustomersService;
import com.yhd.object.store.StoreMerchantStoreInfo;
import com.yhd.response.store.StoreGetResponse;

import net.sf.json.JSONObject;
@Controller
@RequestMapping(value = "/yhd")
public class YHDController {
	private static final Logger log = LoggerFactory.getLogger(YHDController.class);
	
	
	@Autowired
	private CustomersService customersService;

	
	private final String appKey="10210014020800000879";
	private final String appSecret="1679ebc80f749ad8309c83835673fea7";
	private final String codeURL="https://member.yhd.com/login/authorize.do";
	private final String tokenUrl="https://member.yhd.com/login/token.do";
	private final String testUrl="https://member.yhd.com/testOauth/testAuthorizeResult.do";
	
	private final String APIUrl="http://openapi.yhd.com/app/api/rest/router";
	
	private final String redirect_uri="http://wms.paiu.com.cn/wms/yhd/code&scope=&state=&view=";
	@RequestMapping(value = "")
	public String init(HttpServletRequest request, HttpServletResponse response) {
		
		JSONObject json=null;
		PrintWriter out=null;
	    try {
	    	json=new JSONObject();
	    	out=response.getWriter();
	    	
	    	log.info("一号店商家应用调用");
	    	Enumeration<String> keys=request.getParameterNames();
	    	while(keys.hasMoreElements()){
	    		String key=keys.nextElement();
	    		log.info("参数名称:"+key+"====参数内容:"+request.getParameter(key));
	    	}
	    
	    	return "redirect:https://member.yhd.com/login/authorize.do?client_id=10210014020800000879&response_type=code&redirect_uri="+redirect_uri;
	    	
	    	
		} catch (Exception e) {
			json.put("status", "0");
			json.put("content", e.getMessage());
			out.print(json.toString());
			//log.error("error",e);
		}
		return appKey;
	}
	
	@RequestMapping(value = "code")
	public String code(HttpServletRequest request, HttpServletResponse response) {
		
		JSONObject json=null;
		PrintWriter out=null;
	    try {
	    	json=new JSONObject();
	    	out=response.getWriter();
	    	log.info("一号店商家应用调用");
	    	Enumeration<String> keys=request.getParameterNames();
	    	while(keys.hasMoreElements()){
	    		String key=keys.nextElement();
	    		//log.info("参数名称:"+keys.nextElement()+"====参数内容:"+request.getParameter(key));
	    	}
	    	 String code=request.getParameter("code");
	    	 Map<String, String> param = new HashMap<String, String>();
	    	 param.put("grant_type", "authorization_code");
	    	 param.put("code", code);
	    	 param.put("client_id", appKey);
	    	 param.put("client_secret", appSecret);
	    	 param.put("redirect_uri", "http://wms.paiu.com.cn/wms/yhdlogin/");
	    	 param.put("scope", "item");
	    	 param.put("view", "web");
	    	 param.put("state", "");
	    	 String result=WebUtils.doPost(tokenUrl, param, 3000, 3000);
	    	 json=JSONObject.fromObject(result);
	    	 String sessionKey=json.getString("accessToken");
	    	 String userId=json.getString("userId");
	    	 String nickName=json.getString("nickName");
	    	 String userCode=json.getString("userCode");
	    	 String userType=json.getString("userType");
	    	 String merchantId=json.getString("merchantId");
	    	 
	    	log.info("第二次获取授权返回的结果:"+result);
	    	log.info("accessToken:"+json.getString("accessToken"));
	    	//log.info("expiresIn:"+json.getString("expiresIn"));
	    	log.info("userId:"+json.getString("userId"));
	    	log.info("nickName:"+json.getString("nickName"));
	    	log.info("userCode:"+json.getString("userCode"));
	    	log.info("userType:"+json.getString("userType"));
	    	
	    	
	    	//log.info("merchantId:"+json.getString("merchantId"));
	    	//log.info("supplierId:"+json.getString("supplierId"));
	    	//log.info("isvId:"+json.getString("isvId"));
	    	out=response.getWriter();
			json=new JSONObject();
			
			try {
				StoreGetResponse storeGetResponse=YHDStore.getStoreGetResponse(APIUrl, appKey, appSecret, sessionKey);
				StoreMerchantStoreInfo storeMerchantStoreInfo=storeGetResponse.getStoreMerchantStoreInfo();
				if(storeMerchantStoreInfo!=null){
					YhdSessionKeyVo ysko=new YhdSessionKeyVo();
					ysko.setMerchantId(merchantId);
					ysko.setNickName(nickName);
					ysko.setSessionKey(sessionKey);
					ysko.setUserCode(userCode);
					ysko.setUserId(userId);
					ysko.setUserType(userType);
					User user=this.customersService.registerYhd(ysko, storeMerchantStoreInfo);
					return "redirect:/yhdlogin/"+user.getUsername()+"/"+user.getOpenPassword();
				}
			} catch (Exception e) {
				
			}
		} catch (Exception e) {
			json.put("status", "0");
			json.put("content", e.getMessage());
			out.print(json.toString());
			//log.error("error",e);
		}
		return "redirect:/v2/login";
	}
	
	
	
	
}
